<template>
	<div class="tikuBg">
		
		<div class="banner">
			<image src="https://www.baixuemianshi.com/zhuanti/images/swiper_xcx2.jpg" mode="widthFix"></image>
		</div>
		<div class="tabsBox">
			<u-tabs :list="moshiList" @change="changeMoshi" :scrollable="false"></u-tabs>
		</div>
		<div class="loadBox" v-if="searchLoading">
			<u-loading-icon size="36" mode="circle" :vertical="true" color="red" text="加载中..." textSize="20"></u-loading-icon>
		</div>
		
		<div class="zutiBox" v-if="selectMoshi.name == '出题模式'">
			<div class="item">
				<div class="btnBox">
					<div class="btn"><u-button type="error" text="添加新题组+" @click="showZuti = true"></u-button></div>
					<div class="btn"><u-button type="success" text="查看全部所选题目" @click="toAllSelect"></u-button></div>
				</div>
			</div>
			<div class="item" v-for="(item,index) in zutiReverse" :key="index">
				<div  @click="getTimuDetail(item)">
					<h3>{{ item.title }}</h3>
					<div class="type"><u-tag :text="item.type" type="error"></u-tag></div>
					<div class="info">{{item.info.tao}}套-每套{{item.info.ti}}题</div>
				</div>
				
				<div class="deleteItem">
					<u-button type="warning" size="mini" text="删除题组" plain @click.stop="deleteItem(item)"></u-button>
					<div class="space"></div>
					<u-button type="error" size="mini" text="取消推送" plain @click.stop="cancelStudent(item)" v-if="item.toStudent"></u-button>
					<u-button type="error" size="mini" text="推给学员" @click.stop="toStudent(item)" v-else></u-button>
				</div>
			</div>
		</div>
		
		<div class="zutiBox" v-else>
			<div class="item">
				<div class="btnBox">
					<div class="btn"><u-button type="error" text="添加新作业+" @click="showZuoye = true"></u-button></div>
				</div>
			</div>
			<div class="item" v-for="(item,index) in homeworkReverse" :key="index">
				<h3 @click="getZuoyeList(item)">{{ item.title }}</h3>
				
				<div class="deleteItem">
					<!-- <u-button type="error" size="mini" text="删除" @click.stop="deleteZuoye(item)"></u-button> -->
				</div>
			</div>
		</div>
		
		
		<u-popup :show="showZuti" @close="showZuti = false" mode="center" :safeAreaInsetBottom="false">
			<div class="popContent">
				<h3>创建新题组</h3>
				<div class="inp">
					<u-cell :title="newTizu.moshi" :isLink="true" @click="showSelectmoshi =  true"></u-cell>
				</div>
				<div class="inp">
					<u-cell :title="newTizu.date" :isLink="true" @click="showSelectDate = true"></u-cell>
				</div>
				<div class="inp">
					<u-cell :title="newTizu.noon" :isLink="true" @click="showSelectNoon = true"></u-cell>
				</div>
				<div class="inp">
					<u-cell :title="newTizu.msVal" :isLink="true" @click="showSelectMs = true"></u-cell>
				</div>
				
				<template v-if="newTizu.moshi == '套题模式'">
					<div class="inp">
						<u-cell :title="newTizu.time + '（分钟）'" :isLink="true" @click="showSelectTime = true"></u-cell>
					</div>
					<div class="inp">
						<u-cell :title="newTizu.tao + '（套）'" :isLink="true" @click="showSelectTao = true"></u-cell>
					</div>
					<div class="inp">
						<u-cell :title="newTizu.ti + '（题）'" :isLink="true" @click="showSelectTi = true"></u-cell>
					</div>
				</template>
				<div class="btnBox">
					<u-button type="error" text="立即创建" @click="addTizu"></u-button>
				</div>
			</div>
		</u-popup>
		<u-picker :show="showSelectmoshi" :columns="[pickDetail.msList]" @confirm="pickerMoshi" @cancel="showSelectmoshi = false" :immediateChange="true"></u-picker>
		<u-datetime-picker :show="showSelectDate" mode="date" :minDate="1704038400000"  @confirm="pickerDate" @cancel="showSelectDate = false"></u-datetime-picker>
		<u-picker :show="showSelectTime" :columns="[pickDetail.time]" @confirm="pickerTime" @cancel="showSelectTime = false" :immediateChange="true"></u-picker>
		<u-picker :show="showSelectNoon" :columns="[pickDetail.noons]" @confirm="pickerNoon" @cancel="showSelectNoon = false" :immediateChange="true"></u-picker>
		<u-picker :show="showSelectMs" :columns="[pickDetail.moshis]" @confirm="pickerMs" @cancel="showSelectMs = false" :immediateChange="true"></u-picker>
		<u-picker :show="showSelectTao" :columns="[pickDetail.tao]" @confirm="pickerTao" @cancel="showSelectTao = false" :immediateChange="true"></u-picker>
		<u-picker :show="showSelectTi" :columns="[pickDetail.ti]" @confirm="pickerTi" @cancel="showSelectTi = false" :immediateChange="true"></u-picker>
		
		
		<u-popup :show="showZuoye" @close="showZuoye = false" mode="center" :safeAreaInsetBottom="false">
			<div class="popContent">
				<h3>创建新作业</h3>
				<div class="inp">
					<u-cell :title="newZuoye.date" :isLink="true" @click="showSelectDate2 = true"></u-cell>
				</div>
				
				<div class="btnBox">
					<u-button type="error" text="立即创建" @click="addZuoye"></u-button>
				</div>
			</div>
		</u-popup>
		<u-datetime-picker :show="showSelectDate2" mode="date" :minDate="1704038400000" @confirm="pickerDate2" @cancel="showSelectDate2 = false"></u-datetime-picker>
		
		
		<canvas canvas-id="waterMark" class="waterMark" style="width: 100vw; height: 100vh;"></canvas>
		<image :src="waterMarkUrl" class="waterMark-bg" style="width: 100vw; height: 100vh;"></image>
	</div>
</template>

<script>
	import {
		mapActions
	} from 'vuex';
	const db = wx.cloud.database()
	export default {
		data() {
			return {
				waterMarkUrl: "",
				windowWidth: 100,
				windowHeight: 100,
				userinfo: {},
				nolimit: false,
				limitStatus:false,
				moshiList: [
					{name: "出题模式",spell: "zuti"},
					{name: "作业模式",spell: "homework"},
				],
				selectMoshi:{name: "出题模式",spell: "zuti"},
				banjiDetail:"",
				showZuti: false,
				newTizu:{
					moshi:"请选择答题模式",
					noon: "请选择时段",
					date: "请选择日期",
					time:"请选择答题时间",
					tao: "请选择套数",
					ti: "请选择每套题数",
					msVal:"请选择练习模式"
				},
				pickDetail:{
					msList:['刷题模式','套题模式'],
					noons:['上午','下午','晚上'],
					moshis:['听题模式','看题模式'],
					time: Array.from({ length: 99 }, (_, index) => index + 1),
					tao: Array.from({ length: 10 }, (_, index) => index + 1),
					ti: Array.from({ length: 20 }, (_, index) => index + 1),
				},
				showSelectmoshi: false,
				showSelectDate:false,
				showSelectDate2:false,
				showSelectTime:false,
				showSelectTao:false,
				showSelectTi: false,
				showSelectNoon: false,
				showSelectMs: false,
				
				showZuoye: false,
				newZuoye:{
					date: "请选择日期",
				},
				searchLoading:true,
				allSelect:[]
			}
		},
		onShareAppMessage(res) {
			if (res.from === 'button') { // 来自页面内分享按钮
				return {
					title: `题库-学员端`, //分享标题
					path: '/pages/nbhd/tiku/student', //分享页面路径
					imageUrl: '', //分享图标
					desc: '雪恒教育-白雪面试', //自定义分享描述 
				}
			} else {
				return {
					title: `题库-学员端`, //分享标题
					path: '/pages/nbhd/tiku/student', //分享页面路径
					imageUrl: '', //分享图标
					desc: '雪恒教育-白雪面试', //自定义分享描述 
				}
			}
		},
		onLoad(options) {
			
		},
		onReady(e) {
			
		},
		onShow() {
			if(wx.setVisualEffectOnCapture){
			    wx.setVisualEffectOnCapture({
			        visualEffect: 'hidden',
			        success:(res) => {
			            console.log('success回调',res)
			        },
			    })
			}
			this.getTimuInfo()
		},
		onHide() {
			if(wx.setVisualEffectOnCapture){
			    wx.setVisualEffectOnCapture({
			        visualEffect: 'none',
			        success:(res) => {
			            console.log('success回调',res)
			        },
			    })
			}
		},
		computed: {
			userphone() {
				return this.$store.getters.userphone ? this.$store.getters.userphone : '';
			},
			selectBanji(){
				return this.$store.getters.selectBanji ? this.$store.getters.selectBanji : '';
			},
			zutiReverse(){
				if(this.banjiDetail){
					let arr = this.banjiDetail.zuti
					arr = [...arr].reverse()
					return arr
				}else{
					return []
				}
			},
			homeworkReverse(){
				if(this.banjiDetail){
					let arr = this.banjiDetail.homework
					arr = [...arr].reverse()
					return arr
				}else{
					return []
				}
			},
		},
		created() {
			let that = this;
			
		},
		mounted() {
			let that = this 
			
			wx.hideLoading()
			if(that.userphone){
				that.drawWaterMark(that.userphone);
			}else{
				that.drawWaterMark('雪恒教育-白雪面试');
			}
		},
		watch: {},
		methods: {
			...mapActions(['LogSetPhone','LogSetBanji']),
			drawWaterMark(text) {
				this.getDeviceInfo().then(response => {
					const w = response.windowWidth;
					const h = response.windowHeight;
					this.windowWidth = w;
					this.windowHeight = h;
					//创建canvas绘制上下文
					const canvas = uni.createCanvasContext("waterMark", this);
					canvas.clearRect(0, 0, w, h)
					//开始创建一个路径，需要调用fill或者stroke才会使用路径进行填充或描边。
					canvas.beginPath();
					canvas.setFontSize(18);
					canvas.setFillStyle('rgba(0, 0, 0, 0.1)');
					canvas.rotate(-30 * Math.PI / 180)
					if (text) {
						text = this.trim(text)
					}
					const maxWidth = text.length * 18
					for (let x = 0; x < 10; x++) {
						for (let y = 0; y < 20; y++) {
							//在画布上绘制被填充的文本。
							canvas.fillText(text, (maxWidth + 40) * x - 400, 90 * y + 20);
						}
					}
					//将之前在绘图上下文中的描述（路径、变形、样式）画到 canvas 中。
					canvas.draw(false, () => {
						//把当前画布指定区域的内容导出生成指定大小的图片
						uni.canvasToTempFilePath({
							canvasId: "waterMark",
							complete: (res) => {
								this.waterMarkUrl = res.tempFilePath
							}
						}, this)
					})
				});
			},
			trim(str) {
				let trimStr = '';
				const reg = /[\t\r\f\n\s]*/g;
				if (typeof str === 'string') {
					trimStr = str.replace(reg, '');
				}
				return trimStr
			},
			/**
			 * 获取当前设备的信息
			 * **/
			getDeviceInfo() {
				return new Promise((resolve, reject) => {
					uni.getSystemInfo({
						success: (sysInfo) => {
							resolve(sysInfo)
						}
					})
				})
			},
			changeMoshi(e){
				this.selectMoshi = {
					name: e.name,
					spell: e.spell
				}
			},
			getTimuInfo(){
				let that = this
				db.collection('nbhd_tiku_banji').where({
					banji: that.selectBanji
				}).get({
					success: function(res) {
						if(res.data.length > 0){
							that.banjiDetail = res.data[0]
							that.searchLoading = false
						}else{
							that.pushEmpty()
						}
					}
				})
			},
			pushEmpty(){
				let that = this
				db.collection('nbhd_tiku_banji').add({
					data: {
						banji: that.selectBj,
						zuti:[],
						homework:[],
						allSelect:[],
						homeSelect:[],
						sijiaoke:""
					},
					success: function(res) {
						that.getTimuInfo()
					}
				})
			},
			getTimuDetail(info){
				uni.navigateTo({
					url:'./editTimu?title=' + info.title
				})
			},
			pickerMoshi(e){
				this.newTizu.moshi = e.value[0]
				this.showSelectmoshi = false
			},
			pickerDate(e){
				let t = uni.$u.timeFormat(e.value, 'yyyy-mm-dd');
				this.newTizu.date = t
				this.showSelectDate = false
			},
			pickerDate2(e){
				let t = uni.$u.timeFormat(e.value, 'yyyy-mm-dd');
				this.newZuoye.date = t
				this.showSelectDate2 = false
			},
			pickerTime(e){
				this.newTizu.time = e.value[0]
				this.showSelectTime = false
			},
			pickerNoon(e){
				this.newTizu.noon = e.value[0]
				this.showSelectNoon = false
			},
			pickerMs(e){
				this.newTizu.msVal = e.value[0]
				this.showSelectMs = false
			},
			pickerTao(e){
				this.newTizu.tao = e.value[0]
				this.showSelectTao = false
			},
			pickerTi(e){
				this.newTizu.ti = e.value[0]
				this.showSelectTi = false
			},
			addTizu(){
				let that = this
				if(that.newTizu.moshi == '请选择答题模式'){
					uni.showToast({
						icon:"error",
						title:"请选择模式"
					})
					return
				}
				if(that.newTizu.date == '请选择日期'){
					uni.showToast({
						icon:"error",
						title:"请选择日期"
					})
					return
				}
				if(that.newTizu.noon == '请选择时段'){
					uni.showToast({
						icon:"error",
						title:"请选择时段"
					})
					return
				}
				if(that.newTizu.msVal == '请选择练习模式'){
					uni.showToast({
						icon:"error",
						title:"请选择练习模式"
					})
					return
				}
				
				if(that.newTizu.moshi == '套题模式'){
					if(that.newTizu.time == '请选择答题时间'){
						uni.showToast({
							icon:"error",
							title:"请选择答题时间"
						})
						return
					}
					if(that.newTizu.tao == '请选择套数'){
						uni.showToast({
							icon:"error",
							title:"请选择套数"
						})
						return
					}
					if(that.newTizu.ti == '请选择每套题数'){
						uni.showToast({
							icon:"error",
							title:"请选择每套题数"
						})
						return
					}
				}
				let newObj = {}
				if(that.newTizu.moshi == '套题模式'){
					newObj = {
						type: that.newTizu.moshi,
						title:that.newTizu.date + '-' + that.newTizu.moshi + '-' + that.newTizu.noon + '-' + that.newTizu.msVal + '-' + that.newTizu.tao + '套-' + that.newTizu.ti + '道题' + '-' + that.newTizu.time + '分钟',
						list: new Array(that.newTizu.tao).fill().map(() => new Array()),
						info:{tao:that.newTizu.tao,ti:that.newTizu.ti},
						toStudent:false
					}
				}else{       
					newObj = {
						type: that.newTizu.moshi,
						title:that.newTizu.date + '-' + that.newTizu.moshi + '-' + that.newTizu.noon + '-' + that.newTizu.msVal,
						list:[],
						info:{tao:1,ti:20},
						toStudent:false
					}
				}
				
				let titleList = that.banjiDetail.zuti.map(item => item.title)
				if(titleList.includes(newObj.title)){
					uni.showToast({
						icon:'error',
						title:"已创建同类题组"
					})
					return 
				}
				that.banjiDetail.zuti.push(newObj)
				that.filterAllSelect()
				that.showZuti = false
				that.getTimuDetail({title:newObj.title})
			},
			deleteItem(info){
				let that = this
				wx.showModal({
					title:"确认删除？",
					content: '一旦删除无法恢复',
					success (res) {  
					    if (res.confirm) {  
							that.searchLoading = true
							that.banjiDetail.zuti = that.banjiDetail.zuti.filter(item => item.title != info.title)
							that.filterAllSelect()
					    } else if (res.cancel) {  
							console.log('用户点击取消')  
					    }  
					}
				})
				
			},
			filterAllSelect(){
				let that = this
				let allArr = []
				that.banjiDetail.zuti.map((item,index) => {
					if(item.type=="刷题模式"){
						item.list.map((t,j) => {
							t.zTitle = item.title
							allArr.push(t)
						})
					}else{
						item.list.map((t,j) => {
							t.map(l => {
								l.zTitle = item.title
								allArr.push(l)
							})
						})
					}
				})
				that.allSelect = allArr
				that.updateZuti()
			},
			deleteZuoye(info){
				let that = this
				wx.showModal({
					title:"确认删除？",
					content: '一旦删除无法恢复',
					success (res) {  
					    if (res.confirm) {  
							that.banjiDetail.homework = that.banjiDetail.homework.filter(item => item.title != info.title)
							that.updateZuoye()
					    } else if (res.cancel) {  
							console.log('用户点击取消')  
					    }  
					}
				})
			},
			updateZuti(){
				let that = this
				db.collection('nbhd_tiku_banji').doc(that.banjiDetail._id).update({
					data:{
						allSelect: that.allSelect,
						zuti: that.banjiDetail.zuti
					},
					success: res => {
						that.getTimuInfo()
					}
				})
			},
			toAllSelect(){
				let that = this
				uni.navigateTo({
					url:'./allSelect'
				})
			},
			addZuoye(){
				let that = this
				let newObj = {}
				newObj = {
					title:that.newZuoye.date + '作业',
					list:[],
				}
				let titleList = that.banjiDetail.homework.map(item => item.title)
				if(titleList.includes(newObj.title)){
					uni.showToast({
						icon:'error',
						title:"已创建同类作业"
					})
					return 
				}
				that.banjiDetail.homework.push(newObj)
				that.updateZuoye(newObj)
				
			},
			updateZuoye(newObj){
				let that = this
				db.collection('nbhd_tiku_banji').doc(that.banjiDetail._id).update({
					data:{
						homework: that.banjiDetail.homework
					},
					success: res => {
						that.showZuoye = false
						that.getZuoyeList({title:newObj.title})
					}
				})
			},
			getZuoyeList(info){
				uni.navigateTo({
					url:'./editZuoye?title=' + info.title
				})
			},
			toStudent(info){
				let that = this
				let selectIndex = -1
				that.banjiDetail.zuti.map((item,index) => {
					if(item.title == info.title){
						selectIndex = index
					}
				})
				that.banjiDetail.zuti[selectIndex].toStudent = true
				that.filterAllSelect()
			},
			cancelStudent(info){
				let that = this
				let selectIndex = -1
				that.banjiDetail.zuti.map((item,index) => {
					if(item.title == info.title){
						selectIndex = index
					}
				})
				that.banjiDetail.zuti[selectIndex].toStudent = false
				that.filterAllSelect()
			}
		},
		components: {
			
		}
	};
</script>

<style scoped>
	@import url(./index.css);
	.tabsBox{background-color: #fff;}
	.zutiBox{}
	.zutiBox .item{position: relative; width: 650rpx; margin: 30rpx auto 0; background-color: #fff; padding: 25rpx; border-radius: 15rpx; box-shadow: 0 0 15rpx rgba(0,0,0,.2);}
	.zutiBox .item h3{font-size: 30rpx; font-weight: bold;}
	.zutiBox .item .type{display: flex; margin: 20rpx 0;}
	.zutiBox .item .info{font-size: 28rpx; }
	
	.popContent h3{font-size: 34rpx; font-weight: bold; text-align: center; margin-bottom: 15rpx;}
	.deleteItem{display: flex; position: absolute; right: 25rpx; bottom: 25rpx; z-index: 10;}
	.deleteItem .space{width: 15rpx;}
	.btnBox{display: flex; justify-content: space-between;}
	.btnBox .btn{width: 48%;}
</style>